package ai.people.core.security.intercept;

import ai.people.core.security.properties.CloudSecurityProperties;
import ai.people.netmon.framework.constant.CloudConstant;
import ai.people.netmon.framework.exception.enums.AuthExceptionEnum;
import ai.people.netmon.framework.exception.type.AuthException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 拦截跳过网关的请求
 *
 * @author yuanqinglong
 * @date 2022/2/15 15:53
 */
@Slf4j
public class RequestSecurityInterceptor implements HandlerInterceptor {

    private final CloudSecurityProperties cloudSecurityProperties;

    public RequestSecurityInterceptor(CloudSecurityProperties cloudSecurityProperties) {
        this.cloudSecurityProperties = cloudSecurityProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!cloudSecurityProperties.getOnlyFetchByGateway()) {
            return true;
        }
//        //白名单方法直接返回
//        HandlerMethod handlerMethod = (HandlerMethod) handler;
//        //获取类上的注解
//        WhiteMethod classAnnotation = handlerMethod.getMethod().getDeclaringClass().getAnnotation(WhiteMethod.class);
//        //获取方法上的注解
//        WhiteMethod methodAnnotation = handlerMethod.getMethodAnnotation(WhiteMethod.class);
//        if (classAnnotation != null || methodAnnotation != null) {
//            return true;
//        }
//
//        //白名单ip直接返回
//        String ipAddress = IpAddressUtil.getIpAddress(request);
//        Set<Whitelist> whitelist = cloudSecurityProperties.getWhitelist();
//        if (CollectionUtils.isNotEmpty(whitelist) && StringUtils.isNotBlank(ipAddress)) {
//            for (Whitelist list : whitelist) {
//                //配置的ip地址
//                String addresses = list.getAddresses();
//                if(ipAddress.replaceAll(addresses,"").length() == 0){
//                    //配置的资源地址
//                    Set<String> resource = list.getResource();
//                    if (CollectionUtils.isNotEmpty(resource)) {
//                        //处理资源地址
//                    }
//                    return true;
//                }
//            }
//        }
        // 网关增加请求头标识
        String token = request.getHeader(CloudConstant.GATEWAY_TOKEN_HEADER);
        // 网关增加请求头内容
        String gatewayToken = new String(Base64Utils.encode(CloudConstant.GATEWAY_TOKEN_VALUE.getBytes()));
        if (!Objects.equals(gatewayToken, token)) {
            log.warn("跨网关访问{}", request.getRequestURI());
            throw new AuthException(AuthExceptionEnum.UNAUTHORIZED_ACCESS);
        }
        return true;

    }
}
